package qm.com.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import qm.com.dao.QingmingDao;
import qm.com.dto.QingMingActive;

@Repository
public class QingmingDaoImpl implements QingmingDao {

	@Resource
	private JdbcTemplate jdbcTemplate;

	public int insertQMActive(QingMingActive qingMingActive) throws Exception {
		String sql = "insert into qingming (play,eat) values(?,?)";

		return this.jdbcTemplate.update(
				sql,
				new Object[] { qingMingActive.getPlay(),
						qingMingActive.getEat() });
	}

	public List<QingMingActive> selectQMActive(String eat) throws Exception {
		String sql = "select play,eat from qingming where eat = ?";
		return this.jdbcTemplate.query(sql, new Object[] { eat }, new QMList());
	}

	/**
	 * 使用了内部类的方法 使这个可以实现ROWMapper接口。实现了多重继承。
	 * 
	 * */
	private class QMList implements RowMapper<QingMingActive> {

		public QingMingActive mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			QingMingActive qingMingActive = new QingMingActive();
			qingMingActive.setEat(rs.getString("eat"));
			qingMingActive.setPlay(rs.getString("play"));
			return qingMingActive;
		}
	}

	public int updateQMAction(QingMingActive qingMingActive) throws Exception {
		
		String sql = "update qingming set play = ? where eat = ?";
		return this.jdbcTemplate.update(
				sql,
				new Object[] { qingMingActive.getPlay(),
						qingMingActive.getEat() });
	}

	public int deleteQMAction(String eat) throws Exception {
		String sql = "delete from  qingming where eat = ?" ;
		return this.jdbcTemplate.update(sql,new Object[]{eat});
	}

	/**
	 * 
	 * 利用map来查询数据
	 * 
	 * */
	public QingMingActive selectQMActionMap(String eat) throws Exception {
		String sql = "select * from qingming where ear =?";
		Map map = this.jdbcTemplate.queryForMap(sql, new Object[]{eat});
		
		QingMingActive qingMingActive = new QingMingActive();
		
		qingMingActive.setEat((String)map.get("eat"));
		qingMingActive.setPlay((String)map.get("play"));
		return qingMingActive;
	}
}